<!--
 * @Author: guo wei
 * @LastEditors: [guo wei]
 * @LastEditTime: 2024-03-06 22:56:14
 * @Description: 
-->
<template>
  <div class="wrap" :class="step == 4 ? 'already-wrap' : ''">
    <div class="container-left">
      <div class="info-content" v-if="step == 1">
        <div class="header-img">
          <img src="@/assets/images/banner-title.png" alt="" />
        </div>
        <div class="line-one">
          只需上传建筑模型，实现一键导出对应 <span>立面控制手册反反复复付</span>
        </div>
        <div class="line-two">为了生成更符合您要求的立控手册</div>
        <div class="line-two">建议您创建好需导出的立面场景</div>
        <div class="line-two">如不创建, 我们会帮您导出正东南西北立面...</div>
      </div>
      <div class="info-content" v-if="step == 2 || step == 3">
        <div class="header-img">
          <img src="@/assets/images/building.png" alt="" />
        </div>
      </div>
      <div class="info-content info-screen-content" v-if="step == 4">
        <div class="header-img">
          <img src="@/assets/images/building.png" alt="" />
        </div>
      </div>
    </div>
    <div class="container-right">
      <div class="right-header">
        <span @click="login" v-if="!isLogin">登录</span>
        <span v-else @click="goHome">{{ loginName }}</span>
        <el-divider direction="vertical" />
        <span> 快速注册 </span>
      </div>
      <div class="right-content" v-if="step == 1">
        <div class="border-box" v-if="isLogin">
          <el-upload class="upload-demo" :on-change="handleChange" :file-list="fileList" drag :limit="1" action="#"
            :auto-upload="false">
            <div class="img-wrap">
              <div class="upload-img">
                <img src="@/assets/images/false.svg" alt="" />
              </div>
            </div>
          </el-upload>
        </div>
        <div class="border-box" v-else>
          <div class="img-wrap" @click="goRouterIndex">
            <div class="upload-img">
              <img src="@/assets/images/false.svg" alt="" />
            </div>
          </div>
        </div>
        <div class="box-tip">目前仅支持sketchup，如需更多模型支持，点击</div>
      </div>
      <div class="right-content" v-else-if="step == 2">
        <div class="border-box step-one-box">
          <div class="right-content-title">
            模型信息 | <span class="active">类型</span>
          </div>
          <el-form label-width="120px" :model="formInline" class="demo-form-inline">
            <el-form-item label="建筑类型">
              <el-cascader v-model="formInline.building" :options="buildingData" :props="cascaderProps" />
            </el-form-item>
          </el-form>
        </div>
        <div class="step-operate-btn">
          <el-button @click="step = 3">稍后填写</el-button>
          <el-button type="primary" @click="step = 3">下一步</el-button>
        </div>
      </div>
      <div class="right-content" v-else-if="step == 3">
        <div class="border-box step-two-box">
          <div class="right-content-title">
            模型信息 | <span class="active">色系/档次</span>
          </div>
          <el-form label-width="120px" :model="formInline" class="demo-form-inline">
            <el-form-item label="色系">
              <el-select v-model="formInline.colorSys" @change="changeColorSys" placeholder="选择色系" clearable>
                <el-option v-for="item in colorSysOptions" :key="item.colorSystemInfoId" :label="item.colorSystemName"
                  :value="item.colorSystemInfoId" />
              </el-select>
            </el-form-item>
            <el-form-item label="颜色">
              <el-select multiple v-model="formInline.color" placeholder="选择颜色">
                <el-option v-for="item in colorInfoOptions" :key="item.colorInfoId" :label="item.colorName"
                  :value="item.colorInfoId" />
              </el-select>
            </el-form-item>
            <el-form-item label="档次">
              <el-radio-group v-model="formInline.grade">
                <el-radio-button v-for="item in gradeInfoOptions" :key="item.gradeInfoId" :label="item.gradeName" />
              </el-radio-group>
              <!-- <el-select v-model="formInline.grade" placeholder="选择档次">
                <el-option
                  v-for="item in gradeInfoOptions"
                  :key="item.gradeInfoId"
                  :label="item.gradeName"
                  :value="item.gradeInfoId"
                />
              </el-select> -->
            </el-form-item>
          </el-form>
        </div>
        <div class="step-operate-btn">
          <el-button @click="step = 4">稍后填写</el-button>
          <el-button type="primary" @click="confirmModifyModel">完成</el-button>
        </div>
      </div>
      <div class="right-bottom">更喜欢插件？</div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import cache from "@/plugins/cache";
import * as qiniu from "qiniu-js";
import SparkMD5 from "spark-md5";
import { allBuildingTypeInfo } from "@/api/building-type.js";
import {
  getInitMultipartUploadWithPublic,
  getPublicFileUrl,
} from "@/api/login";
import {
  getInfoSysSelectData,
  getColorInfoSelectData,
  getGradeInfoSelectData,
  addModelInfoData,
  modifyModelInfoData,
  getModelInfoDetailData,
  getModelListData,
} from "@/api/model";
import { UploadFilled } from "@element-plus/icons-vue";
import Cookies from "js-cookie";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const publicFileUrl = ref("");
const formInline = reactive({
  building: [],
  colorSys: "",
  color: [],
  grade: "",
});
const cascaderProps = {
  value: "buildingTypeInfoId",
  label: "buildingTypeName",
};
const buildingData = ref([]);
const colorSysOptions = ref([]);
const colorInfoOptions = ref([]);
const gradeInfoOptions = ref([]);
const loginName = ref("");
onMounted(() => {
  publicFileUrl.value = cache.session.getJSON("publicUrl");

  const name = cache.local.get("loginName");
  if (name != null) {
    getListData();
    getColorSysListData();
    getColorListData();
    getGradeListData();
    isLogin.value = true;
    step.value = 1;
    loginName.value = name;
  }
  console.log("name", name);
});
onUnmounted(() => {
  clearInterval(timer.value);
  timer.value = null;
});
const getListData = async () => {
  const params = { count: true, pageId: 1, pageSize: 20 };
  try {
    const res = await allBuildingTypeInfo();
    // const res = await buildingTypeInfos(params);
    if (res.code == 200) {
      buildingData.value = res.result || [];
    }
  } catch (error) { }
};
const goHome = () => {
  router.push("/list/model-list");
}
const getColorSysListData = async () => {
  const params = { count: true, pageId: 1, pageSize: 20 };
  try {
    const res = await getInfoSysSelectData();
    if (res.code == 200) {
      colorSysOptions.value = res.result || [];
    }
  } catch (error) { }
};

const getModelDetail = async (id) => {
  try {
    const res = await getModelInfoDetailData(id);
    if (res.code == 200) {
      console.log("模型明细", res);
      if (res.result.modelStatus == "2") {
        const fileRes = await getPublicFileUrl({
          resourceKey: res.result.elevation,
        });
        setTimeout(() => {
          router.push({
            path: "/report",
            query: {
              modelId: res.result.modelInfoId,
            },
          });
        }, 1000);
        console.log("模型明细", fileRes);
      }
    }
  } catch (error) { }
};

const changeColorSys = () => {
  getColorListData();
};
const getColorListData = async () => {
  const params = {
    count: true,
    pageId: 1,
    pageSize: 20,
    colorSystemValue: formInline.colorSys,
  };
  try {
    const res = await getColorInfoSelectData(params);
    // const res = await buildingTypeInfos(params);
    if (res.code == 200) {
      colorInfoOptions.value = res.result.list || [];
    }
  } catch (error) { }
};

const getGradeListData = async () => {
  const params = {
    count: false,
    pageId: 1,
    pageSize: 20,
  };
  try {
    const res = await getGradeInfoSelectData(params);

    if (res.code == 200) {
      gradeInfoOptions.value = res.result.list || [];
    }
  } catch (error) { }
};

const isLogin = ref(false);

const timer = ref();
onMounted(() => {
  // isLogin.value = cache.session.getJSON("sessionObj") ? true : false;
  // // userInfo.value = cache.session.getJSON("sessionObj")
  // //   ? JSON.parse(cache.session.getJSON("sessionObj").data)
  // //   : {};
  // // console.log(userInfo.value);
  // step.value = 1;
});
const initData = () => {
  timer.value = setInterval(() => {
    clearInterval(timer.value);
    getModelDetail(modifyData.value.modelInfoId);
  }, 1000);
};
const router = useRouter();
const goRouterIndex = () => {
  ElMessage({
    message: "尚未登录，请登录",
    type: "error",
  });
  setTimeout(() => {
    router.push("/login");
  }, 1500);
};
const login = () => {
  router.push("/login");
};
const step = ref(1);
const fileList = ref([]);
const handleChange = (file, files) => {
  let md5 = "";
  const sparkMD5 = new SparkMD5();
  const reader = new FileReader();
  reader.readAsText(file.raw);
  reader.onload = async (event) => {
    //获取文件MD5
    const str = event.target.result;
    sparkMD5.append(str);
    md5 = sparkMD5.end();

    const [fileName, extension] = file.name.split(".");
    const params = {
      md5: md5,
      modelInfoName: fileName,
      modelSize: file.raw.size,
      modelType: extension,
    };
    const res = await addModelInfoData(params);
    console.log("获取文件MD5", res);
    if (res.code == 200) {
      let newDataInfo = res.result;
      if (res.result.isExist) {
        // ElMessage({
        //   message: "该模型已存在",
        //   type: "error",
        // });
        let fileInfo = res.result.encodedObjectName;
        modifyModel(file, fileInfo, params, newDataInfo);
      } else {
        ElMessage({
          message: "模型新增成功",
          type: "success",
        });
        uploadfunc(
          file,
          res.result.upToken,
          res.result.encodedObjectName,
          params,
          newDataInfo
        );
      }
    }
  };
};
const uploadfunc = async (file, uploadtoken, key, params, newDataInfo) => {
  const config = {
    useCdnDomain: true,
    domain: publicFileUrl.value,
    chunkSize: 10,
    forceDirect: false,
  };
  const putExtra = {
    fname: file.name, //文件原始文件名
    params: {},
    mimeType: "",
  };
  const observable = qiniu.upload(file.raw, key, uploadtoken, putExtra, config);
  observable.subscribe({
    next: (result) => {
      console.log("上传成功下一步。", result);
    },
    error: (err) => {
      //上传错误后触发
      console.log("上传失败", err);
    },
    complete: (result) => {
      console.log("上传成功后触发", result);
      //上传成功后触发。包含文件地址。
      if (result.code == 200) {
        // ruleForm[prop] =
        //   [{ url: publicFileUrl.value + result.result.key || "" }] || [];
        ElMessage({
          message: "上传成功",
          type: "success",
        });
        let fileInfo = result.result.key;
        modifyModel(file, fileInfo, params, newDataInfo);
      }
    },
  });
};
const modifyData = ref({});
const modifyModel = async (file, fileInfo, params, newDataInfo) => {
  const temp = {
    encodedObjectName: fileInfo,
    modelInfoName: params.modelInfoName,
    md5: params.md5,
    modelInfoId: newDataInfo.modelInfoId,
    modelSize: newDataInfo.modelSize,
    modelType: newDataInfo.modelType,
    recordVersion: newDataInfo.recordVersion,
    // buildingTypeName: formInline.building,
    // colorSystemValue: formInline.color,
    // gradeName: formInline.grade,
  };
  step.value = 2;
  modifyData.value = temp;
};
const confirmModifyModel = async () => {
  step.value = 4;
  const temp = {
    ...modifyData.value,
    buildingTypeName: formInline.building.join(","),
    colorSystemValue: formInline.color.splice(-1).join(","),
    gradeName: formInline.grade,
  };
  // console.log("临时数据", temp);
  // return;
  const res = await modifyModelInfoData(temp);
  if (res.code == 200) {
    ElMessage({
      message: "模型添加成功",
      type: "success",
    });
    // getModelDetail(modifyData.value.modelInfoId);
    initData();
  }
  console.log("临时数据", res);
};
</script>
<style lang="scss" scoped>
.wrap {
  width: 100%;
  display: flex;
  height: 100%;
  background: #e0e0e0;

  &.already-wrap {
    .container-left {
      width: 100%;
    }

    .container-right {
      display: none;
    }
  }

  .container-left {
    background: #000;
    width: 52%;
    height: 100%;
    border-radius: 0 15px 15px 0;
    display: flex;
    justify-content: center;

    // // align-items: center;
    // flex-direction: column;
    .info-content {
      width: 400px;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      //   align-items: center;
    }

    .info-screen-content {
      // width: 100%;
    }

    .header-img {}

    .line-one {
      color: #fff;
      font-size: 14px;
      margin-top: 15px;
      margin-left: 20px;
      display: inline-block;

      border-bottom: 1px solid #efa86e;

      span {
        color: #efa86e;
      }
    }

    .line-two {
      color: #fff;
      font-size: 12px;
      margin-top: 15px;
      padding-left: 20px;
    }
  }

  .container-right {
    flex: 1;
    display: flex;
    flex-direction: column;

    .right-content-title {
      color: #000;
      font-size: 20px;
      text-align: center;

      .active {
        color: #2e04d0;
      }
    }

    .right-header {
      text-align: right;
      padding: 15px 25px;
      height: 80px;
      display: flex;
      align-items: center;
      justify-content: end;

      span {
        cursor: pointer;
      }
    }

    .right-content {
      flex: 1;
      width: 80%;
      background: #fff;
      border-radius: 10px;
      margin: 0 auto;
      padding: 30px 23px;
      padding-bottom: 0;
      display: flex;
      flex-direction: column;

      .border-box {
        flex: 1;
        border: 1px dashed #d9d9d9;

        &.step-one-box {
          padding: 30px;
          display: flex;
          flex-direction: column;

          .demo-form-inline {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;

            .el-form-item {
              margin-bottom: 8%;
            }

            .el-select {
              width: 100%;
            }
          }
        }

        &.step-two-box {
          padding: 30px;
          display: flex;
          flex-direction: column;

          .demo-form-inline {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;

            .el-form-item {
              margin-bottom: 8%;
            }

            .el-select {
              width: 100%;
            }
          }
        }
      }

      .step-operate-btn {
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: end;
      }

      .box-tip {
        padding: 10px 0;
      }
    }

    .right-bottom {
      height: 160px;
      width: 80%;

      padding-top: 30px;

      margin: 0px auto;
    }
  }
}

.img-wrap {
  width: 100%;
  height: 100%;
  display: flex;
  cursor: pointer;
  align-items: center;
  justify-content: center;
}

.upload-demo {
  height: 100%;

  .upload-img {
    width: 150px;
    height: 80px;

    img {
      width: 100%;
      height: 100%;
    }
  }

  :deep .el-upload {
    height: calc(100% - 50px);

    .el-upload-dragger {
      height: 100%;
    }
  }
}
</style>
